package com.chao.search;

/**
 * @author : Rookie
 * @description : 插值查找
 * @date : 2023/7/3
 */
public class InterpolationSearch {

    public static void main(String[] args) {
        int[] arr = new int[] {0,2,5,6,8,13,35,41};
        int target = 8;
        int result = search(arr, target);
        System.out.println(result);
    }

    private static int search(int []arr,int target) {
        int left = 0,right = arr.length -1,index = -1;
        while (left < right) {
            int pos = left + ((target - arr[left]) * (right - left)) / (arr[right] - arr[left]);
            if (arr[pos] > target) {
                right = pos - 1;
            } else if (arr[pos] < target) {
                left = pos + 1;
            } else {
                index = pos;
                break;
            }
        }
        return index;
    }
}
